//
//  UINavigationController+MFAPMCrashMonitor.m
//  AvoidCrash
//
//  Created by zhang liyu on 2019/5/27.
//

#import "UINavigationController+MFAPMCrashMonitor.h"
#import "UIViewController+MFAPMCrashMonitor.h"

#import "NSObject+MFAPMSwizzle.h"
#import <objc/runtime.h>

extern const char kMFAPMCrashMonitorVCLeaksCheckKey;
@implementation UINavigationController (MFAPMCrashMonitor)

#pragma mark - Initial Actions

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [[self class] mfapm_swizzleInstanceSEL:@selector(popToViewController:animated:) toSEL:@selector(mfapm_popToViewController:animated:)];
        [[self class] mfapm_swizzleInstanceSEL:@selector(popToRootViewControllerAnimated:) toSEL:@selector(mfapm_popToRootViewControllerAnimated:)];
        [[self class] mfapm_swizzleInstanceSEL:@selector(popViewControllerAnimated:) toSEL:@selector(mfapm_popViewControllerAnimated:)];
    });
}

#pragma mark - Exchange Handle Actions

- (nullable NSArray<__kindof UIViewController *> *)mfapm_popToViewController:(UIViewController *)viewController animated:(BOOL)animated{
    NSArray<__kindof UIViewController *> *resultArr = [self mfapm_popToViewController:viewController animated:animated];
    for (UIViewController *popVC in resultArr){
        [self setDidLeakWithVC:popVC];
    }
    return resultArr;
}

- (nullable NSArray<__kindof UIViewController *> *)mfapm_popToRootViewControllerAnimated:(BOOL)animated{
    NSArray<__kindof UIViewController *> *resultArr = [self mfapm_popToRootViewControllerAnimated:animated];
    for (UIViewController *popVC in resultArr){
        [self setDidLeakWithVC:popVC];
    }
    return resultArr;
}

- (nullable UIViewController *)mfapm_popViewControllerAnimated:(BOOL)animated{
    UIViewController *resultVC = [self mfapm_popViewControllerAnimated:animated];
    [self setDidLeakWithVC:resultVC];
    return resultVC;
}

#pragma mark - Setter & Getter

- (void)setDidLeakWithVC:(UIViewController *)VC{
    if(!VC){
        return;
    }
    //OBJC_ASSOCIATION_ASSIGN
    objc_setAssociatedObject(VC, &kMFAPMCrashMonitorVCLeaksCheckKey, @(YES), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end
